import React, {useState, useEffect} from 'react'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { IncomeIcon, ExpenseIcon, AdjustmentIcon, ExportIcon, EmptyIcon, DeleteIcon, TransferIcon } from '@components/icon/system';
import { Button, Modal } from 'antd';
import classNames from 'classnames';
import Icon from '@components/icon';
import http from '@utils/http'
import './styles/index.less'

const { confirm } = Modal;

const AccountPage = (props) => {
  const [accountInfo, setAccountInfo] = useState({});
  const [transactionList, setTransactionList] = useState([]);
  const [hasNext, setHasNext] = useState(false);
  const [tab, setTab] = useState('');
  const { id } = useParams();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const query = Object.fromEntries(searchParams.entries());

  const { assetId, assetName, accountName } = query;

  useEffect(() => {
    getAccountInfo()
    getTransactionList()
  }, [])

  const getAccountInfo = () => {
    http.get('accountInfo', {
      accountId: id
    }).then(res => {
      if (res.code !== 200) return false
      console.log(res.data)
      setAccountInfo(res.data)
    })
  }
  /**
   * 获取交易列表数据
   * @param {string} type - 交易类型，默认为空字符串
   * @returns {void}
   */
  const getTransactionList = (type = '') => {
    // 发起HTTP请求获取交易列表
    http.get('transactionList', {
      accountId: id,
      action: type,
      page: 1,
      pageSize: 20
    }).then(res => {
      // 检查响应状态码，非200时直接返回
      if (res.code !== 200) return false
      console.log('transactionList', res.data)
      // 设置交易列表数据
      setTransactionList(res.data.list)
      // 设置是否还有下一页数据
      setHasNext(res.data.hasNext)
    })
  }
  const handelDelete = () => {
    confirm({
      title: '是否确认删除该账户？',
      icon: <ExclamationCircleOutlined />,
      content: '删除账户后将无法进行恢复是否确认删除',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        console.log('OK');
      }
    });
  }

  /**
   * 切换标签页并获取对应类型的交易列表
   * @param {string} type - 标签页类型
   * @returns {void}
   */
  const changeTab = (type) => {
    setTab(type)
    getTransactionList(type)
  }

  const { amount, name, billDate, dueDate, assetName: accountAssetName, icon } = accountInfo

  return (
    <>
      <div className="account-page">
        <div className="account-header">
          <div className="asset-retreat-button" onClick={() => navigate(-1)}></div>
          <div className="breadcrumb">
            <a href="#" onClick={(e) => {e.preventDefault(); navigate('/')}} className="breadcrumb-item">我的资产</a>
            <a href="#" onClick={(e) => {e.preventDefault(); navigate(`/asset/${assetId}?name=${assetName}`)}} className="breadcrumb-item">{assetName}</a>
            <span className="breadcrumb-item">{accountName}</span>
          </div>
        </div>
        <div className="account-main">
          <div className="account-left">
            <div className="account-statistics">
              <ul>
                <li>
                  <div className="statistics-title">账户余额</div>
                  <div className="statistics-count amount-family">{amount}</div>
                </li>
                <li className="divider"></li>
                <li>
                  <div className="statistics-title">累计资金转入</div>
                  <div className="statistics-count amount-family">0.00</div>
                </li>
                <li className="divider"></li>
                <li>
                  <div className="statistics-title">累计资金转出</div>
                  <div className="statistics-count amount-family">0.00</div>
                </li>
                <li className="divider"></li>
                <li>
                  <div className="statistics-title">最后更新时间</div>
                  <div className="statistics-count amount-family">2025-03-12</div>
                </li>
              </ul>
            </div>
            <div className="account-transaction">
              <ul className="account-transaction-tab">
                <li className={classNames({'active': tab === ''})} onClick={() => changeTab('')}>全部</li>
                <li className={classNames({'active': tab === 'INCOME'})} onClick={() => changeTab('INCOME')}>转入</li>
                <li className={classNames({'active': tab === 'EXPENSE'})} onClick={() => changeTab('EXPENSE')}>转出</li>
                <li className={classNames({'active': tab === 'ADJUSTMENT'})} onClick={() => changeTab('ADJUSTMENT')}>调整</li>
              </ul>
              <div className="account-transaction-list">
                {
                  transactionList.map(item => (
                    <div className="account-transaction-item" key={item.id}>
                      <div className="transaction-item-left">
                        {
                          item.action === 'INCOME' && (
                            <>
                              <div className="transaction-icon income-icon"><IncomeIcon width={24} height={24} fill="#333" /></div>
                              <div className="transaction-title">转入</div>
                            </>
                          )
                        }
                        {
                          item.action === 'EXPENSE' && (
                            <>
                              <div className="transaction-icon expense-icon"><ExpenseIcon width={24} height={24} fill="#333" /></div>
                              <div className="transaction-title">转出</div>
                            </>
                          )
                        }
                        {
                          item.action === 'ADJUSTMENT' && (
                            <>
                              <div className="transaction-icon adjustment-icon"><AdjustmentIcon width={24} height={24} fill="#333" /></div>
                              <div className="transaction-title">调整</div>
                            </>
                          )
                        }
                      </div>
                      <div className="transaction-item-right">
                        <div className="transaction-amount amount-family">{item.amount}</div>
                        <div className="transaction-time">{item.createdAt}</div>
                      </div>
                    </div>
                  ))
                }
              </div>
            </div>
          </div>
          <div className="account-right">
            <div className="account-card">
              <div className="account-card-header">
                <Icon path={icon} width="32" height="32" fill="#333" />
                <span className="card-tag">{accountAssetName}</span>
              </div>
              <div className="account-card-title">
                <div className="card-label">账户名称</div>
                <div className="card-name">{name}</div>
              </div>
              <div className="account-card-footer">
                {
                  billDate && (
                    <div className="card-footer-item">
                      <div className="footer-label">账单日</div>
                      <div className="footer-value">{billDate}</div>
                    </div>
                  )
                }
                {
                  dueDate && (
                    <div className="card-footer-item">
                      <div className="footer-label">还款日</div>
                      <div className="footer-value">{dueDate}</div>
                    </div>
                  )
                }
              </div>
            </div>
            <div className="operating-floor">
              <Button type="text" className="delete-btn" onClick={() => handelDelete()}><DeleteIcon width={16} height={16} fill="#FF0000" />删除账户</Button>
              <Button type="text" className="export-btn" onClick={() => handelDelete()}><ExportIcon width={16} height={16} fill="#333" />导出账单</Button>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

export default AccountPage;